﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Resources;
using EHTWebsite.Code;
using System.Text;
using System.IO;
using System.Net;
using System.Web.Security;
using EHTWebsiteProject.Code.Entity;
using EHTWebsiteProject.Code.BLL;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTProductUI : System.Web.UI.Page
    {
        private String message = "";
        private DataTable dtProductCategorys = new DataTable();
        private Int32 ProductID = HangSo.DEFAULT_ID;
        public Boolean IsVN = true;
        private String languageCode = "vi-VN";
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources"));

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dtProductCategorys = DanhMucSanPhamProvider.GetDanhMucSanPhams(-1, "", "").Tables[0];
                try
                {
                    languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                    if (languageCode == "en-us")
                    {
                        IsVN = false;
                    }

                }
                catch (Exception ex)
                {
                }

                try
                {
                    ProductID = Int32.Parse(Request.QueryString["ProductID"]);
                }
                catch
                {

                }

                try
                {
                    message = Request.QueryString["Message"].ToString();
                    if (message != "")
                        ltrErorr.Text = HelpMethod.ApplySuccess(message);
                }
                catch
                {

                }
                Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                LoadLanguage(Thread.CurrentThread.CurrentCulture);

                CreateDDLCategory(0, 0);
                if (IsVN == true)
                    this.ddlDanhMucSanPham.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
                else
                    this.ddlDanhMucSanPham.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));

                if (ProductID != -1)
                {
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Edit_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Edit_Other;
                    LoadProduct(ProductID);
                }
                else
                {
                    ViewState["action"] = HangSo.ACTION_ADD;
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Add_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Add_Other;
                }
            }
        }

        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbSave.Text = rm.GetString("lbSave", ci);
            lbCancel.Text = rm.GetString("lbCancel", ci);
            lbApply.Text = rm.GetString("lbApply", ci);
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbDanhMucSanPham.Text = rm.GetString("lbDanhMucSanPham", ci);
            lbThuTu.Text = rm.GetString("lbThuTu", ci);
            lbGiamGia.Text = rm.GetString("lbGiamGia", ci);
            lbGroup.Text = rm.GetString("lbGroup", ci);
            lbHinhAnh.Text = rm.GetString("lbHinhAnh", ci);            
            lbNoiBat.Text = rm.GetString("lbNoiBat", ci);
            lbNoiDungOther.Text = rm.GetString("lbNoiDungOther", ci);
            lbNoiDungVN.Text = rm.GetString("lbNoiDungVN", ci);
            lbProducts.Text = rm.GetString("lbProducts", ci);
            lbTenSanPhamOther.Text = rm.GetString("lbTenSanPhamOther", ci);
            lbTenSanPhamVN.Text = rm.GetString("lbTenSanPhamVN", ci);
            lbPrice.Text = rm.GetString("lbPrice", ci);   
        }


        /// <summary>
        /// Ham load danh muc san pham
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtProductCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucID"].ToString());
                ListItem li = new ListItem(preString + drCategorysSub[i]["TenDanhMucVN"].ToString(), drCategorysSub[i]["DanhMucID"].ToString());
                this.ddlDanhMucSanPham.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }


        /// <summary>
        /// Ham kiem tra du lieu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public Boolean ValidateData()
        {
            Boolean flag = true;
            if (txtMaSku.Text == "" || txtTenSanPhamVN.Text =="")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                flag = false;
            }
            if (ddlDanhMucSanPham.SelectedValue == "-1")
            {
                if (IsVN == true)
                    message = HangSo.meagessddl;
                else
                    message = HangSo.meagessddlOther;
                flag = false;
            }

            else
            {
                DataSet ds = DanhMucSanPhamProvider.GetDanhMucSanPhams(Int32.Parse(ddlDanhMucSanPham.SelectedValue),"","");
                if (ds.Tables[0].Rows.Count > 1)
                {
                    if (IsVN == true)
                        message = HangSo.Eorr_Add;
                    else
                        message = HangSo.Eorr_AddOther;
                    flag = false;
                }
            }
                       
            return flag;
        }

        public Boolean check()
        {
            Boolean flag = true;
            DataSet Sku = SanPhamProvider.Check_Product(txtMaSku.Text, "", "");
            DataSet NameVN = SanPhamProvider.Check_Product("", txtTenSanPhamVN.Text, "");
            DataSet NameOther = SanPhamProvider.Check_Product("", "", txtTenSanPhamOther.Text);

            if (Sku.Tables[0].Rows.Count > 0)
            {
                if (IsVN == true)
                    message = HangSo.check_Sku;
                else
                    message = HangSo.check_SkuOther;
                txtMaSku.Focus();
                flag = false;
            }

            if (NameVN.Tables[0].Rows.Count > 0)
            {
                if (IsVN == true)
                    message = HangSo.check_TenSp;
                else
                    message = HangSo.check_TenSpOther;
                txtTenSanPhamVN.Focus();
                flag = false;
            }

            if (NameOther.Tables[0].Rows.Count > 0)
            {
                if (IsVN == true)
                    message = HangSo.check_TenSp;
                else
                    message = HangSo.check_TenSpOther;
                txtTenSanPhamOther.Focus();
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// Ham find du lieu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void LoadProduct(Int32 ProductID)
        { 
             SanPham theSanPham = SanPhamProvider.GetSanPhamBySanPhamID(ProductID);
             txtGiamGIa.Text = theSanPham.GiamGia.ToString();
             txtGroup.Text = theSanPham.SanPhamLienQuan;
             txtMaSku.Text = theSanPham.MaSku;
             txtTenSanPhamOther.Text = theSanPham.TenSanPhamOther;
             txtTenSanPhamVN.Text = theSanPham.TenSanPhamVN;
             txtPrice.Text = String.Format("{0:0,0}", theSanPham.DonGia);
             txtThuTu.Text = theSanPham.SapXep.ToString();
             ddlDanhMucSanPham.SelectedValue = theSanPham.DanhMucID.ToString();            
             fckNoiDungOther.Value = theSanPham.NoiDungOther;
             fckNoiDungVN.Value = theSanPham.NoiDungVN;
             ckNoiBat.Checked = theSanPham.NoiBat;
             ImageProduct.ImageUrl = "~/ImageDatas/Products/"+theSanPham.HinhAnhUrl;
             ViewState["ProductID"] = ProductID.ToString();
             ViewState["HinhAnhUrl"] = theSanPham.HinhAnhUrl.ToString();
             ViewState["action"] = HangSo.ACTION_UPDATE;
        }

        protected void ImgSave_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();

            Int32 SanPhamIDOut = 0;

            if(ValidateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            SanPham theSanPham = new SanPham();
            theSanPham.DanhMucID = Int32.Parse(ddlDanhMucSanPham.SelectedValue);
            try
            {
                theSanPham.DonGia = float.Parse(txtPrice.Text);
                theSanPham.GiamGia = float.Parse(txtGiamGIa.Text);
                theSanPham.SapXep = Int32.Parse(txtThuTu.Text);
            }
            catch
            {
                theSanPham.DonGia = 0;
                theSanPham.GiamGia = 0;
                theSanPham.SapXep = 1;
            }
            theSanPham.MaSku = txtMaSku.Text;
            theSanPham.MoTaOther = "";
            theSanPham.MoTaVN = "";
            theSanPham.NoiBat = ckNoiBat.Checked;
            theSanPham.NoiDungOther = fckNoiDungOther.Value.Trim();
            theSanPham.NoiDungVN = fckNoiDungVN.Value.Trim();
            theSanPham.Publish = true;
            theSanPham.SanPhamLienQuan = txtGroup.Text;
            theSanPham.TenSanPhamOther = txtTenSanPhamOther.Text;
            theSanPham.TenSanPhamVN = txtTenSanPhamVN.Text;

            if (this.FileUploadImage.HasFile)
            {
                String fileName = FileUploadImage.PostedFile.FileName;
                String pathAvatars = Server.MapPath("~/");
                String fileType = Path.GetExtension(fileName);
                String FileNewName = DateTime.Now.Ticks.ToString() + fileType;
                try
                {
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(FileUploadImage.PostedFile.InputStream);
                    if (Int32.Parse(oImg.Width.ToString()) > 400)
                    {


                        int thumbWidth = 400;
                        int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oThumbNail.Save(pathAvatars + "\\ImageDatas\\Products\\" + FileNewName);
                        theSanPham.HinhAnhUrl = FileNewName;
                        oImg.Dispose();
                    }

                    else
                    {

                        this.FileUploadImage.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + FileNewName);
                        theSanPham.HinhAnhUrl = FileNewName;
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    theSanPham.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
                else
                {
                    theSanPham.HinhAnhUrl = "noImage.gif";
                }

            }

            if (action == HangSo.ACTION_ADD)
            {
                if (check() == false)
                {
                    ltrErorr.Text = HelpMethod.ErorrLogin(message);
                    return;
                }

                theSanPham.SanPhamID = -1;
                SanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, true);
            }
            else
            {
                theSanPham.SanPhamID = Int32.Parse(ViewState["ProductID"].ToString());
                SanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, false);
            }

            Response.Redirect("EHTProducts.aspx");

        }

        protected void ImgApply_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();

            Int32 SanPhamIDOut = 0;

            if (ValidateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            SanPham theSanPham = new SanPham();
            theSanPham.DanhMucID = Int32.Parse(ddlDanhMucSanPham.SelectedValue);
            try
            {
                theSanPham.DonGia = float.Parse(txtPrice.Text);
                theSanPham.GiamGia = float.Parse(txtGiamGIa.Text);
                theSanPham.SapXep = Int32.Parse(txtThuTu.Text);
            }
            catch
            {
                theSanPham.DonGia = 0;
                theSanPham.GiamGia = 0;
                theSanPham.SapXep = 1;
            }
            theSanPham.MaSku = txtMaSku.Text;
            theSanPham.MoTaOther = "";
            theSanPham.MoTaVN = "";
            theSanPham.NoiBat = ckNoiBat.Checked;
            theSanPham.NoiDungOther = fckNoiDungOther.Value.Trim();
            theSanPham.NoiDungVN = fckNoiDungVN.Value.Trim();
            theSanPham.Publish = true;
            theSanPham.SanPhamLienQuan = txtGroup.Text;
            theSanPham.TenSanPhamOther = txtTenSanPhamOther.Text;
            theSanPham.TenSanPhamVN = txtTenSanPhamVN.Text;

            if (this.FileUploadImage.HasFile)
            {
                String fileName = FileUploadImage.PostedFile.FileName;
                String pathAvatars = Server.MapPath("~/");
                String fileType = Path.GetExtension(fileName);
                String FileNewName = DateTime.Now.Ticks.ToString() + fileType;
                try
                {
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(FileUploadImage.PostedFile.InputStream);
                    if (Int32.Parse(oImg.Width.ToString()) > 400)
                    {


                        int thumbWidth = 400;
                        int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oThumbNail.Save(pathAvatars + "\\ImageDatas\\Products\\" + FileNewName);
                        theSanPham.HinhAnhUrl = FileNewName;
                        oImg.Dispose();
                    }

                    else
                    {

                        this.FileUploadImage.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + FileUploadImage.FileName);
                        theSanPham.HinhAnhUrl = FileUploadImage.FileName;
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    theSanPham.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
                else
                {
                    theSanPham.HinhAnhUrl = "~//ImageDatas//Products//noImage.gif";
                }

            }

            if (action == HangSo.ACTION_ADD)
            {
                if (check() == false)
                {
                    ltrErorr.Text = HelpMethod.ErorrLogin(message);
                    return;
                }

                theSanPham.SanPhamID = -1;

                SanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, true);
            }
            else
            {
                theSanPham.SanPhamID = Int32.Parse(ViewState["ProductID"].ToString());
                SanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, false);
            }

            Response.Redirect("EHTProductUI.aspx?ProductID="+SanPhamIDOut.ToString());

        }
    }
}